
#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
using namespace std;

namespace MyThread
{
    template<class T>
    using fun_t = function<void(T,string)>;

    template <class T>
    class Thread
    {
    private:
        void excute()
        {
            _func(_pdata,_name);
        }

    public:
        Thread(fun_t<T> func, T pdata, const string&name="noname")
            : _func(func), _pdata(pdata), _name(name), _stop(true) {}

        static void *threadrun(void *args)//如果不是静态，会有this指针
        {
            Thread<T> *ptr = reinterpret_cast<Thread<T> *>(args);
            ptr->excute();
            return nullptr;
        }

        bool start()
        {
            int n = pthread_create(&_id, nullptr, threadrun, this);//把this当参数传过去
            if (n == 0)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }
        void join()
        {
            if (!_stop)
            {
                pthread_join(_id, nullptr);
            }
        }
        void detach()
        {
            if (!_stop)
            {
                pthread_detach(_id);
            }
        }
        void stop()
        {
            _stop = true;
        }

    private:
        pthread_t _id;
        string _name;
        bool _stop;
        fun_t<T> _func;
        T _pdata;
    };
}